{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Class Tournament"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import random as rand\n",
    "from tabulate import tabulate\n",
    "from Match import Match, name, print_history\n",
    "from Cooperate import Cooperate\n",
    "from Defect import Defect\n",
    "from Flipper import Flipper\n",
    "from TitForTat import TitForTat\n",
    "\n",
    "cooperate = Cooperate()\n",
    "defect = Defect()\n",
    "flipper = Flipper()\n",
    "titForTat = TitForTat()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Import everyone's rules\n",
    "from AverageTitForTat import AverageTitForTat\n",
    "from CheckAndChoose import CheckAndChoose, np\n",
    "from dbTriCon import dbTriCon\n",
    "from fifty_good import fifty_is_good\n",
    "from Patrick import Patrick\n",
    "from scummyPrisoner import scummyPrisoner\n",
    "from Smart import random, Smart\n",
    "from suspiciousProbingTFT import random, SPTFT\n",
    "from TFTMemory import random, TFTMemory\n",
    "from TitForTwoTats import TitForTwoTats\n",
    "from Trustworthy import random, Trustworthy\n",
    "from ResponsiveTFTMod import ResponsiveTFTMod\n",
    "from suspiciousTitForTat import suspiciousTitForTat\n",
    "\n",
    "averageTitForTat = AverageTitForTat()\n",
    "checkAndChoose = CheckAndChoose()\n",
    "dBTriCon = dbTriCon()\n",
    "fifty_good = fifty_is_good()\n",
    "patrick = Patrick()\n",
    "scummy_Prisoner = scummyPrisoner()\n",
    "smart = Smart()\n",
    "susProbingTFT = SPTFT()\n",
    "tftMemory = TFTMemory()\n",
    "titForTwoTats = TitForTwoTats()\n",
    "trustworthy = Trustworthy()\n",
    "responsiveTFTMod = ResponsiveTFTMod()\n",
    "susTitForTat = suspiciousTitForTat()\n",
    "\n",
    "rule_list = [averageTitForTat, checkAndChoose, dBTriCon, fifty_good, patrick, scummy_Prisoner, smart, susProbingTFT, tftMemory, titForTwoTats, trustworthy, cooperate, defect, flipper, titForTat, responsiveTFTMod, susTitForTat]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class Tournament():\n",
    "\n",
    "    def __init__(self, rule_list, length, identical_match=False):\n",
    "        self.rule_list = rule_list\n",
    "        self.length = length\n",
    "        self.identical_match = identical_match\n",
    "        \n",
    "        self.match_scores = []\n",
    "        self.rule_scores = {}\n",
    "        self.win_diff = []\n",
    "        self.wins = []\n",
    "        \n",
    "        for rule in self.rule_list:\n",
    "            self.rule_scores[name(rule)] = []\n",
    "\n",
    "    def run(self):\n",
    "        for match in self.match_gen():\n",
    "            match.run()\n",
    "            score = match.score()\n",
    "#             self.rule_scores[name(match.rule0)][name(match.rule1)] = score[match.rule0.order]\n",
    "#             self.rule_scores[name(match.rule1)][name(match.rule0)] = score[match.rule1.order]\n",
    "#             self.match_scores[match.name] = score\n",
    "            self.match_scores.append((match.name, score))\n",
    "    \n",
    "            self.rule_scores[name(match.rule0)].append(score)\n",
    "            self.rule_scores[name(match.rule1)].append(score[::-1])\n",
    "\n",
    "    def match_gen(self):\n",
    "        ''' Generator function to return initialized matches from the list of rules'''\n",
    "        l = range(len(self.rule_list))\n",
    "        if self.identical_match:\n",
    "            n = 0\n",
    "        else:\n",
    "            n = 1\n",
    "        for i in l:\n",
    "            for j in l:\n",
    "                \n",
    "                if j < i+n:\n",
    "                    continue\n",
    "                else:\n",
    "                    new_match = Match(self.rule_list[i], self.rule_list[j], self.length)\n",
    "                    yield new_match\n",
    "                    \n",
    "    def all_scores(self):\n",
    "        \n",
    "        self.score_loss_wins()\n",
    "        pass\n",
    "        \n",
    "    \n",
    "    def sort_rule_score(self):\n",
    "        \n",
    "        [scores.sort(reverse=True) for key, scores in self.match_scores.items()]\n",
    "    \n",
    "    def score_loss_wins(self):\n",
    "        ''' Perform scorings based on number of wins/losses/draws. '''\n",
    "        for rule, scores in self.rule_scores.items():\n",
    "            new_scores = [(score[0]-score[1]) for score in scores]\n",
    "            self.win_diff.append((rule, new_scores))\n",
    "            \n",
    "            win = sum([1 if (score>0) else 0 for score in new_scores])\n",
    "            draw = sum([1 if (score==0) else 0 for score in new_scores])\n",
    "            loss = sum([1 if (score<0) else 0 for score in new_scores])\n",
    "            self.wins.append((rule, win, draw, loss))    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "t = Tournament(rule_list, 100)\n",
    "t.run()\n",
    "t.all_scores()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Wins, Losses, and Draws"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "s_w = sorted(t.wins, key=lambda x: x[1], reverse=True)\n",
    "s_d = sorted(t.wins, key=lambda x: x[2], reverse=True)\n",
    "s_l = sorted(t.wins, key=lambda x: x[3], reverse=True)\n",
    "\n",
    "headers = ['Wins', 'Draws', 'Losses']\n",
    "\n",
    "print(tabulate([[s_w[i], s_d[i], s_l[i]] for i in range(len(s_w))], headers=headers))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Raw Points"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Maximum Points in a Match"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "s_ind = sorted(t.match_scores, key=lambda x: max(x[1]), reverse=True)\n",
    "s_col = sorted(t.match_scores, key=lambda x: sum(x[1]), reverse=True)\n",
    "\n",
    "headers = ['Individual', 'Collective']\n",
    "\n",
    "tab_list = []\n",
    "for i in range(len(s_ind)):\n",
    "    split = s_ind[i][0].split('-')\n",
    "    if s_ind[i][1][0] > s_ind[i][1][1]:\n",
    "        rule = split[0]\n",
    "    else:\n",
    "        rule = split[1]\n",
    "    \n",
    "    indiv = (rule, s_ind[i][1])\n",
    "    tab_list.append([indiv, s_col[i]])\n",
    "    # tab_list.append([s_ind[i], s_col[i]])\n",
    "\n",
    "print(tabulate(tab_list, headers=headers))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Maximum Total Points"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "max_list = []\n",
    "\n",
    "for rule, scores in t.rule_scores.items():\n",
    "    total = str(sum([score[0] for score in scores]))\n",
    "    avg = str(sum([score[0] for score in scores])/len(scores))\n",
    "    max_list.append([rule, total, avg])\n",
    "\n",
    "max_list.sort(key=lambda x: x[1], reverse=True)\n",
    "print(tabulate(max_list, headers=['Rule', 'Total Points', 'Average Points']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Point Differences\n",
    "Which rule won by the most points on average? \n",
    "Which lost by the least on average?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "t.rule_scores\n",
    "\n",
    "gr_diff_list = []\n",
    "le_diff_list = []\n",
    "l = len(t.rule_scores)\n",
    "for rule, scores in t.rule_scores.items():\n",
    "    grs = 0\n",
    "    les = 0\n",
    "    for score in scores:\n",
    "        if score[0] > score[1]:\n",
    "            grs += score[0] - score[1] \n",
    "        elif score[1] > score[0]:\n",
    "            les += score[1] - score[0]\n",
    "    gr_diff_list.append([rule, str(grs/l)])\n",
    "    le_diff_list.append([rule, str(les/l)])\n",
    "        \n",
    "gr_diff_list.sort(key=lambda x: float(x[1]), reverse=True)\n",
    "le_diff_list.sort(key=lambda x: float(x[1]))\n",
    "\n",
    "diff_list = []\n",
    "for i in range(len(gr_diff_list)):\n",
    "    diff_list.append([gr_diff_list[i], le_diff_list[i]])\n",
    "\n",
    "headers = ['Won by Most', 'Lost by Least']\n",
    "\n",
    "print(tabulate(diff_list, headers=headers))"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
